package com.huixi.config.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.huixi.config.Annotation.LoginRequired;
import com.huixi.config.properties.JwtProperties;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUrl = request.getRequestURL().toString();
        String contextPath = request.getContextPath();
        if (!checkNeedLogin(handler)) {
            return true;
        }

        log.debug("请求url={}没有访问权限，需要登录！", requestUrl);
        response.sendRedirect(contextPath + "/login.html");
        return false;
    }

    /**
     * 判断是否需要登录拦截，是返回true，否返回false
     */
    private boolean checkNeedLogin(Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return false;
        }

        HandlerMethod method = (HandlerMethod) handler;
        //判断方法上是否具有@LoginRequired注解
        boolean hasLoginAnnotation = method.getMethod().isAnnotationPresent(LoginRequired.class);
        if (!hasLoginAnnotation) {
            return false;
        }

        //注解值为false，也无需登录
        LoginRequired loginRequired = method.getMethod().getAnnotation(LoginRequired.class);
        if (!loginRequired.required()) {
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }


}
